package org.pearl.springboot.minio.boot;

import io.minio.errors.MinioException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by TD on 2021/10/21
 */
@Slf4j
@ControllerAdvice
public class MinioExceptionControllerAdvice {

    // 最后异常处理器,没被匹配到的Exception异常都由这里处理
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Map<String,Object> errorHandler(Exception ex) {
        ex.printStackTrace();
        return getExceptionModel(500,ex.getMessage(),ex.getClass().getName(), Arrays.toString(ex.getStackTrace()));
    }

    // 处理NoHandlerFoundException Exception
    @ResponseBody
    @ExceptionHandler(value = MinioException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Map<String,Object> errorHandler(MinioException ex) {
        ex.printStackTrace();
        return getExceptionModel(503,ex.getMessage(),ex.getClass().getName(),Arrays.toString(ex.getStackTrace()));
    }

    // 获取异常中的信息封装为MAP
    private Map<String,Object> getExceptionModel(int code,String msg,String execName,String stackTrace){
        Map<String,Object> map = new HashMap<>();
        map.put("code", code);
        map.put("msg",msg);
        map.put("execName",execName);
        map.put("stackTrace", stackTrace);
        return map;
    }
}

